package com.ec.mn.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ec.mn.entity.Notification;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface NotificationMapper extends BaseMapper<Notification> {
    @Select("SELECT * FROM notification WHERE receiver_id = #{receiverId} ORDER BY send_time DESC")
    List<Notification> selectByReceiverId(@Param("receiverId") Long receiverId);

    @Select("SELECT * FROM notification WHERE sender_id = #{senderId} ORDER BY send_time DESC")
    List<Notification> selectBySenderId(@Param("senderId") Long senderId);

    @Select("SELECT * FROM notification WHERE receiver_id = #{receiverId} AND status = 0 ORDER BY send_time DESC")
    List<Notification> selectUnreadByReceiverId(@Param("receiverId") Long receiverId);

    @Select("SELECT * FROM notification WHERE receiver_id = #{receiverId} AND status = 1 ORDER BY send_time DESC")
    List<Notification> selectReadByReceiverId(@Param("receiverId") Long receiverId);

    @Update("UPDATE notification SET status = 1, read_time = #{readTime} WHERE id = #{id}")
    int markAsRead(@Param("id") Long id, @Param("readTime") LocalDateTime readTime);

    @Update("UPDATE notification SET status = 2 WHERE id = #{id}")
    int markAsDeleted(@Param("id") Long id);

    @Select("SELECT COUNT(*) FROM notification WHERE receiver_id = #{receiverId} AND status = 0")
    Long countUnreadByReceiverId(@Param("receiverId") Long receiverId);

    @Select("SELECT COUNT(*) FROM notification WHERE receiver_id = #{receiverId} AND status = 1")
    Long countReadByReceiverId(@Param("receiverId") Long receiverId);

    @Select("SELECT * FROM notification WHERE receiver_id = #{receiverId} AND send_time BETWEEN #{startTime} AND #{endTime} ORDER BY send_time DESC")
    List<Notification> selectByTimeRange(@Param("receiverId") Long receiverId,
                                         @Param("startTime") LocalDateTime startTime,
                                         @Param("endTime") LocalDateTime endTime);

    @Select("SELECT * FROM notification WHERE receiver_id = #{receiverId} ORDER BY send_time DESC")
    IPage<Notification> selectPageByReceiverId(Page<Notification> page, @Param("receiverId") Long receiverId);
}
